package com.jiemengshi.server.controller;

import com.jiemengshi.server.model.Feedback;
import com.jiemengshi.server.service.AdminFeedbackService;
import com.jiemengshi.server.service.AdminUserService;
import com.jiemengshi.server.util.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;

@Controller
@RequestMapping(value = {"/admin/feedback"}, produces = {"application/json;charset=UTF-8"})
public class AdminFeedbackController {
    private Logger log = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private AdminFeedbackService feedbackService;

    @Autowired
    private AdminUserService userService;

    @ResponseBody
    @RequestMapping("/reply")
    public String addFeedback(HttpServletRequest request, Feedback feedback){
        try {
            if(StringUtil.isEmpty(feedback.getContent()))
                throw new PrjException(ErrorCodeMsg.FEEDBACK_CONTENT_EMPTY);

            if(feedback.getFeedbackId() < 1)
                throw new PrjException(ErrorCodeMsg.FEEDBACK_ID_ERROR);
            
            feedback.setUserAdminId(userService.getLoginUserId(request));
            if(feedbackService.addFeedback(feedback))
                return ApiResult.SUCCESS;
            else
                throw new PrjException(ErrorCodeMsg.FEEDBACK_ADD_ERROR);
        } catch (PrjException e){
            return ApiResult.writeException(e);
        } catch (Exception e) {
            log.error(ApiJson.toJson(request.getParameterMap()));
            log.error(PrjException.getTrace(e));
            return ApiResult.SYSTEM_ERROR;
        }
    }

    @ResponseBody
    @RequestMapping("/list")
    public String listFeedback(HttpServletRequest request,
                               @RequestParam(required = false, defaultValue = "0") int start,
                               @RequestParam(required = false, defaultValue = "10") int limit){
        try {
            userService.getLoginUserPermissionLevel(request);
            
            if(start == 0)
                return ApiResult.writeData(feedbackService.listFeedback(start, limit), feedbackService.countFeedback());
            else
                return ApiResult.writeData(feedbackService.listFeedback(start, limit));
        } catch (PrjException e){
            return ApiResult.writeException(e);
        } catch (Exception e) {
            log.error(ApiJson.toJson(request.getParameterMap()));
            log.error(PrjException.getTrace(e));
            return ApiResult.SYSTEM_ERROR;
        }
    }
}
